<?php
/**
 * 角色
 * @author xiaojy@wanthings.com
 *
 */
class Role extends BaseActiveRecord
{

    public $column_name = 'name';
    public $module_id = 'role';

    const ADD_ERROR_USING_NAME = -1;
    const ERROR_NOT_FIND = -2;
    const EXECUTE_SUCCESS = 1;

    CONST MAN_STATUS_NORMAL = 1;
    CONST MAN_STATUS_DISABLE = 2;

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return '{{role}}';
    }
    /**
     * 获取特殊权限列表
     * @return [type] [description]
     */
    public function sp($type=1)
    {
        $result = array();
        if($type==1){//承运人
            //订单管理
            $order = array("order/list"=>'订单列表', 'order/detail' => '订单详情', 'order/expenses' => '费用详情', 'order/add' => '新建订单', 'order/edit' => '编辑订单', 'order/receipt' => '回单详情', 'order/onekeyreceipt' => '确认回单', 'order/confirmreceipt' => '确认收单', 'order/usable' => '生效', 'order/disable' => '失效', 'order/allot' => '派单', 'order/autoallot' => '一键派单', 'order/allotcancel' => '取消派单', 'order/merge' => '合并订单', 'order/mergecancel' => '取消合并', 'order/split' => '拆单', 'order/transfersign' => '中转收货', 'order/splitcancel' => '取消拆单', 'order/signself' => '自提', 'order/delete' => '删除订单');
            $result['订单管理'] = $order;

            //调度中心
            $dispat = array( 'order/dispatchlist' => '调度列表','waybill/allocation'=>'调度派车',"waybill/list"=>'运单列表','waybill/detail'=>'运单详情','waybill/express'=>'物流详情','waybill/cancel'=>'取消运单', 'waybill/expressadd'=>'在途登记','waybill/changecar'=>'换车','waybill/updatefee'=>'更改费用', 'order/take' => '揽货', 'order/sign' => '收货');
            $result['调度中心'] = $dispat;


            //运输管理
            $waybill = array( 'order/dispatchlist' => '调度中心','waybill/allocation'=>'调度派车',"waybill/list"=>'运单列表','waybill/detail'=>'运单详情','waybill/express'=>'物流详情','waybill/cancel'=>'取消运单', 'waybill/expressadd'=>'在途登记','waybill/changecar'=>'换车','waybill/updatefee'=>'更改费用', 'order/take' => '揽货', 'order/sign' => '收货');
            $result['运输管理'] = $waybill;




            // 财务管理
            $finance = array('waybill/check'=>'司机结算', 'order/shippersettle' => '货主结算', 'order/carriersettle' => '承运人结算', 'order/editexpenses' => '修改费用', 'order/carrierinvoice' => '待开发票', 'order/shipperinvoice' => '申请开票/已申请开票列表', 'order/finishinvoice' => '开票', 'order/refuseinvoice' => '拒绝开票', 'order/applyinvoice' => '申请开票', 'order/invoicedetail' => '发票详情', 'order/paycheck' => '承运人支付确认');
            $result['财务管理'] = $finance;
            // 数据统计
            $finance = array('statistic/customer'=>'客户收入统计', 'statistic/customerdetail' => '单客户收入支出统计', 'statistic/subcompany' => '子公司利润统计', 'statistic/subcompanydetail' => '单个子公司利润统计', 'statistic/route' => '路线营业额统计', 'statistic/routedetail' => '单个路线营业额统计', 'statistic/customerbill' => '对账单', 'statistic/income' => '收入与回款明细表', 'statistic/account' => '应收账款明细', 'statistic/receipt' => '应收账款回单跟踪明细表', 'statistic/accountdate' => '应收账款账龄统计表', 'statistic/customerexport' => '客户收入/支出统计导出', 'statistic/customerdetailexport' => '客户详细收入/支出统计导出', 'statistic/customerbillexport' => '客户对账单导出', 'statistic/receiptexport' => '应收账款回单导出', 'statistic/subcompanyexport' => '子公司利润导出', 'statistic/subcompanydetailexport' => '单个子公司利润导出', 'statistic/routeexport' => '线路营业额统计导出', 'statistic/routedetailexport' => '单路线营业额统计导出', 'statistic/accountexport' => '应收账款明细导出', 'statistic/accountdateexport' => '应收账款账龄统计导出');
            $result['数据管理'] = $finance;


             //路由管理
            $tmsrouter = array("tmsrouter/add"=>'路由新增','tmsrouter/edit'=>'路由修改','tmsrouter/list'=>'路由列表','tmsrouter/delete'=>'路由删除','tmsrouter/getrouter'=>'路由获取');
            $result['路由配置'] = $tmsrouter;

            //中转点管理
            $tmstransfer = array("tmstransfer/add"=>'中转点新增','tmstransfer/edit'=>'中转点修改','tmstransfer/list'=>'中转点列表','tmstransfer/delete'=>'中转点删除');
            $result['中转点配置'] = $tmstransfer;

            //子公司
            $subsidiary = array("subsidiary/list"=>'子公司列表',"subsidiary/add"=>'子公司添加',"subsidiary/edit"=>'子公司编辑',"subsidiary/delete"=>'子公司删除',"subsidiary/status"=>'子公司禁用');
            $result['子公司配置'] = $subsidiary;

            $partner = array("partner/list"=>'合作伙伴列表',"partner/add"=>'合作伙伴添加',"partner/edit"=>'合作伙伴编辑',"partner/delete"=>'合作伙伴删除',"partner/status"=>'合作伙伴禁用','partner/setbillingrate'=>'合作伙伴设置开票费率');
            $result['合作伙伴配置'] = $partner;

            $client = array("client/list"=>'客户列表',"client/add"=>'客户添加',"client/edit"=>'客户编辑',"client/delete"=>'客户删除',"client/status"=>'客户禁用');
            $result['客户配置'] = $client;

            //预警管理
            $warn = array("warn/add"=>'预警新增','warn/edit'=>'预警修改','warn/list'=>'预警列表','warn/delete'=>'预警删除','warn/addmessage'=>'预警通知配置添加','warn/infomodel'=>'预警消息列表','warn/infoapply'=>'预警消息新增','warn/infodelete'=>'预警消息删除');
            $result['预警配置'] = $warn;


            //车辆管理
            $usercar = array("usercar/add"=>'车辆新增','usercar/edit'=>'车辆修改','usercar/list'=>'车辆列表','usercar/delete'=>'车辆删除','usercar/groupadd'=>'车辆分组新增','usercar/groupdelete'=>'车辆分组删除');
            $result['车辆配置'] = $usercar;

            //发票管理
            $invoice = array("invoice/list"=>'发票',"invoice/list"=>'发票列表',"invoice/edit"=>'发票编辑',"invoice/add"=>'发票添加',"invoice/delete"=>'发票删除');
            $result['发票配置'] = $invoice;

            //用户管理
            $user = array("role/add"=>'角色新增','role/edit'=>'角色修改','role/list'=>'角色列表','role/disable'=>'角色启用','role/delete'=>'角色删除','role/enable'=>'角色启用','user/add'=>'添加用户','user/list'=>'用户列表', 'user/status'=>'用户禁用','user/edit'=>'用户编辑','user/delete'=>'用户删除');
            $result['用户配置'] = $user;


            $driver = array("driver/list"=>'司机列表',"driver/add"=>'司机添加',"driver/edit"=>'司机编辑',"driver/delete"=>'司机删除',"driver/status"=>'司机禁用','driver/look'=>'司机详情');
            $result['司机配置'] = $driver;

            //收/发货人管理
            $address = array("address/add"=>'收/发货人新增','address/edit'=>'收/发货人修改','address/list'=>'收/发货人列表','address/delete'=>'收/发货人删除');
            $result['收/发货人配置'] = $address;

            //路线管理
            $route = array("route/add"=>'路线新增','route/edit'=>'路线修改','route/list'=>'路线列表','route/delete'=>'路线删除');
            $result['常用路线配置'] = $route;
        }else if($type==2){
            //订单管理
            $order = array("order/list"=>'订单列表', 'order/detail' => '订单详情', 'order/expenses' => '费用详情', 'order/add' => '新建订单', 'order/edit' => '编辑订单', 'order/receipt' => '回单详情', 'order/onekeyreceipt' => '确认回单', 'order/confirmreceipt' => '确认收单', 'order/usable' => '生效', 'order/disable' => '失效', 'order/allot' => '派单', 'order/autoallot' => '一键派单', 'order/allotcancel' => '取消派单', 'order/merge' => '合并订单', 'order/mergecancel' => '取消合并', 'order/split' => '拆单', 'order/splitcancel' => '取消拆单', 'order/delete' => '删除订单');
            $result['订单管理'] = $order;

            // 财务管理
            $finance = array('order/carriersettle' => '承运人结算', 'order/editexpenses' => '修改费用', 'order/shipperinvoice' => '申请开票/已申请开票列表', 'order/applyinvoice' => '申请开票', 'order/invoicedetail' => '发票详情', 'order/paycheck' => '承运人支付确认');
            $result['财务管理'] = $finance;

             //路由管理
            $tmsrouter = array("tmsrouter/add"=>'路由新增','tmsrouter/edit'=>'路由修改','tmsrouter/list'=>'路由列表','tmsrouter/delete'=>'路由删除','tmsrouter/getrouter'=>'路由获取');
            $result['路由配置'] = $tmsrouter;

            //中转点管理
            $tmstransfer = array("tmstransfer/add"=>'中转点新增','tmstransfer/edit'=>'中转点修改','tmstransfer/list'=>'中转点列表','tmstransfer/delete'=>'中转点删除');
            $result['中转点配置'] = $tmstransfer;


            $subsidiary = array("subsidiary/list"=>'子公司列表',"subsidiary/add"=>'子公司添加',"subsidiary/edit"=>'子公司编辑',"subsidiary/delete"=>'子公司删除',"subsidiary/status"=>'子公司禁用');
            $result['子公司配置'] = $subsidiary;

            $partner = array("partner/list"=>'合作伙伴列表',"partner/add"=>'合作伙伴添加',"partner/edit"=>'合作伙伴编辑',"partner/delete"=>'合作伙伴删除',"partner/status"=>'合作伙伴禁用','partner/setbillingrate'=>'合作伙伴设置开票费率');
            $result['合作伙伴配置'] = $partner;


            $client = array("client/list"=>'客户列表',"client/add"=>'客户添加',"client/edit"=>'客户编辑',"client/delete"=>'客户删除',"client/status"=>'客户禁用');
            $result['客户配置'] = $client;

            //用户管理
            $user = array("role/add"=>'角色新增','role/edit'=>'角色修改','role/list'=>'角色列表','role/disable'=>'角色启用','role/enable'=>'角色启用','role/delete'=>'角色删除','user/add'=>'添加用户','user/list'=>'用户列表', 'user/status'=>'用户禁用','user/edit'=>'用户编辑','user/delete'=>'用户删除');
            $result['用户配置'] = $user;

            //预警管理
            $warn = array("warn/add"=>'预警新增','warn/edit'=>'预警修改','warn/list'=>'预警列表','warn/delete'=>'预警删除','warn/addmessage'=>'预警通知配置添加','warn/infomodel'=>'预警消息列表','warn/infoapply'=>'预警消息新增','warn/infodelete'=>'预警消息删除');
            $result['预警配置'] = $warn;


            //发票管理
            $invoice = array("invoice/list"=>'发票',"invoice/list"=>'发票列表',"invoice/edit"=>'发票编辑',"invoice/add"=>'发票添加',"invoice/delete"=>'发票删除');
            $result['发票配置'] = $invoice;

            //收/发货人管理
            $address = array("address/add"=>'收/发货人新增','address/edit'=>'收/发货人修改','address/list'=>'收/发货人列表','address/delete'=>'收/发货人删除');
            $result['收/发货人配置'] = $address;

            //路线管理
            $route = array("route/add"=>'路线新增','route/edit'=>'路线修改','route/list'=>'路线列表','route/delete'=>'路线删除');
            $result['常用路线配置'] = $route;
        }else{

        }
        return $result;
    }

    public function getArrByAttributes($arr)
    {
        $result = array();
        $tmp = $this->getByAttributes($arr);
        if (!empty($tmp)) {
            $result = $tmp->attributes;
        }
        return $result;
    }

    public function addRole($arr)
    {
        $id = 0;
        if (!empty($arr['name']) && !$this->isUsingName($arr['name'], $arr['carry_id'])) {
            $this->setIsNewRecord(true);
            $this->name = $arr['name'];
            $this->is_deleted = 0;
            $this->carry_id = $arr['carry_id'];
            $this->status = self::MAN_STATUS_NORMAL;
            if (!empty($arr['status'])) {
                $this->status = $arr['status'];
            }
            if (!empty($arr['sp'])) {
                $this->sp = CJSON::encode($arr['sp']);
            } else {
                $this->sp = '';
            }
            if ($this->save()) {
                $id = $this->id;
            }
        } else {
            $id = self::ADD_ERROR_USING_NAME;
        }
        return $id;
    }

    public function edit($arr)
    {
        $status = false;
        $role = $this->getById($arr['id']);
        if (!empty($role)) {
            $sp = array();
            // if (!empty($arr['name'])) {    //名称不能改
            //     $role->name = $arr['name'];
            // }
            if (!empty($arr['status'])) {
                $role->status = $arr['status'];
            }
            if (!empty($arr['sp'])) {
                $sp = $arr['sp'];
            }
            $role->sp = CJSON::encode($sp);
            $status = $role->save();
            return $status;
        }
        return $status;
    }

    //角色编辑
    public function editAndUser($user_id, $arr)
    {
        $result = array();
        $role = $this->getByIdAndCarry($arr['id'], $user_id);
        if (!empty($role)) {
            $sp = array();
            if (!empty($arr['name'])&&($arr['name']!=$role->name)) {
                if($this->isUsingName($arr['name'], $user_id)){
                    $role->name = $arr['name'];
                }else{
                    $result['errno'] = 3454;
                    $result['errmsg'] = '名称已存在';
                    return $result;
                }
            }
            if (!empty($arr['status'])) {
                $role->status = $arr['status'];
            }
            if (!empty($arr['sp'])) {
                $sp = $arr['sp'];
                $role->sp = CJSON::encode($sp);
            }

            $status = $role->save();
            if($status){
                $result['errno'] = 0 ;
                $result['errmsg'] = 'success';
            }else{
                $result['errno'] = 4323;
                $result['errmsg'] = '保存失败';
            }
        }else{
            $result['errno'] = 4566;
            $result['errmsg'] = '该角色不属于你';
        }
        return $result;
    }

    public function changeStatus($id, $status="disable")
    {
        $result = 0;
        if (in_array($status, array('disable', 'enable'))) {
            $role = $this->getById($id);
            if (!empty($role)) {
                if ($status == "disable") {
                    $role->status = Role::MAN_STATUS_DISABLE;
                } else if ($status == "enable") {
                    $role->status = Role::MAN_STATUS_NORMAL;
                }
                if ($role->save()) {
                    $result = self::EXECUTE_SUCCESS;
                }
            }
        } else {
            $result = self::ERROR_NOT_FIND;
        }
        return $result;
    }

    //删除，传carry_id则需要验证承运人
    public function deleteById($id ,$carry_id = '')
    {
        $result = false;
        if(!empty($carry_id)){
            $role = $this->getByIdAndCarry($id ,$carry_id);
        }else{
            $role = $this->getById($id);
        }
        if (!empty($role)) {
            $role->is_deleted = 1;
            $result = $role->save();
        }
        return $result;
    }

    private function getById($id)
    {
        $result = null;
        $tmp = $this->findByPk($id);
        if (!empty($tmp) && $tmp->is_deleted == 0) {
            $result = $tmp;
        }
        return $tmp;
    }


    private function getByIdAndCarry($id ,$carry_id)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => 0,'id'=>$id, 'carry_id'=>$carry_id));
        $role = Role::model()->find($criteria);
        return $role;
    }

    public function getNameById($id)
    {
        $result = null;
        if (!empty($id)) {
            $tmp = $this->findByPk($id);
            if (!empty($tmp)&&$tmp->name) {
                $result = $tmp->name;
            }
        }
        return $result;
    }
    public function getArrById($id)
    {
        $result = array();
        $tmp = $this->getById($id);
        if (!empty($tmp)) {
            $item = $tmp->attributes;
            if (!empty($item['sp'])) {
                $item['sp'] = CJSON::decode($item['sp']);
            }
            $result = $item;
        }
        return $result;
    }

    private function getByAttributes($arr)
    {
        $result = null;
        $result = $this->findByAttributes(array('is_deleted' => 0, 'name' => $arr['name']));
        return $result;
    }


    public function isUsingName($name, $carry_id)
    {
        $isUsingName = false;
        $role = $this->findByAttributes(array('name' => $name, 'carry_id'=>$carry_id , 'is_deleted'=>0));
        if (!empty($role)) {
            $isUsingName = true;
        }
        return $isUsingName;
    }

    public function roles($filter = array())
    {
        $result = array();
        $roles = array();
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => 0));
        if (!empty($filter['carry_id'])) {
            if(!empty($filter['default_role'])){
                $criteria->addCondition('carry_id='.$filter['carry_id'],'AND');
                $criteria->addCondition('carry_id=""','OR'); //系统默认角色
            }else{
                $criteria->addCondition('carry_id='.$filter['carry_id']);
            }
        }else{
            //查所有
        }
        if(!empty($filter['name'])){
            $criteria->addSearchCondition('name',$filter['name']);
        }
            $criteria->order = 'id desc';    //默认
        $count = $this->count($criteria);
        $pager = array();
        if(!empty($filter['page_size'])||!empty($filter['page'])){
            $pager = new CPagination($count);
            $pager->pageSize = 20;
            if (!empty($filter['page_size'])) {
                $pager->pageSize = $filter['page_size'];
            }
            if (!empty($filter['current_page'])) {
                $pager->setCurrentPage($filter['current_page']);
            }
            $pager->applyLimit($criteria);
        }
        $objects = $this->findAll($criteria);
        if (!empty($objects)) {
            foreach ($objects as $obj) {
                $item = $obj->attributes;
                if (!empty($item['sp'])) {
                    $item['sp'] = CJSON::decode($item['sp']);
                }
                if ($item['name'] == 'admin') {
                    $item['sp'] = array_keys($this->sp());
                }
                $roles[] =  $item;
            }
        }
        $result = array('roles' => $roles, 'pager' => $pager);
        return $result;
    }

    //获取角色权限信息与名称信息。
    public function getByUserSid($sid)
    {
        $result = array();
        $result['errno'] = 0;
        $result['errmsg'] = 'success';
        $user = User::model()->getBySid($sid);
        if($user['errno']!=0){
            return $user;
        }
        if(empty($user['result']['roles'])){
            $result['errno'] = 0;
            $result['errmsg'] = '没有赋予角色';
            $result['result']['sp'] = array();
            $result['result']['names'] = array();
            return $result;
        }
        $roles = $user['result']['roles'];
        $roles = CJSON::decode($roles);
        if(!is_array($roles)){
            $result['errno'] = 4324;
            $result['errmsg'] = '角色不是数组';
            return $result;
        }
        $sp = array();
        $names = array();
        foreach ($roles as $key => $value) {

            $temp = array();
            $role = Role::model()->getArrById($value);
            if($role['status']==Role::MAN_STATUS_DISABLE){
            //被禁用的角色权限取消
                continue;
            }
            if(!empty($role['sp'])){
                $temp = $role['sp'];
            }
            $names[] = $role['name'];
            $sp = array_merge($sp, $temp);

        }
        $result['result']['sp'] = $sp;
        $result['result']['names'] = $names;
        return $result;
    }

    //将sp列表 ,返回  controller/action数组
    public function getSp($sp)
    {
        $action = array();
        if(!empty($sp)){
            foreach ($sp as $k => $v) {
                if(!is_array($v)){
                    return array();
                }
                foreach($v as $s_k=>$s_v){
                    $action[] = $s_k;
                }
            }

        }
        return $action;
    }

    //检查是否有权限
    public function checkSp($sp, $controller, $action)
    {
        $temp = $controller.'/'.$action;
        //$controller_action_list = $this->getSp($sp);
        if(in_array($temp, $sp))
        {
            return true;
        }
        return false;
    }

}

?>